const Client = require('ssh2').Client;

const conn = new Client();

const chalk = require('chalk');

const path = require('path');

const sftpClient = require('ssh2-sftp-client');

const sftp = new sftpClient();

const log = (msg, type = 'green') => console.log(chalk[type](msg));
const config = {
  romote: {
    host: '1.15.99.13',
    port: 22,
    username: 'root',
    password: 'qwedsa123@',
  },
  path: {
    localPath: './dist',
    romotePath: '/usr/local/src/dist',
    shell: 'run.sh',
  },
  docker: {
    image: 'hahaha',
    tag: '0.0.6',
    container: 'my-blog-frontend',
    stopContainer: 'my-blog-frontend', //需要停止运行的容器
  },
};

const putDir = (localPath, romotePath, callback) => {
  sftp
    .connect(config.romote)
    .then(() => {
      log('连接成功,上传中...');
      return sftp.uploadDir(localPath, romotePath);
    })
    .then(data => {
      log('上传成功');
      typeof callback === 'function' && callback();
    })
    .catch(err => {
      log('他妈的上传失败了');
      console.log(err);
    })
    .finally(() => {
      // 断开连接
      sftp.end();
    });
};

conn
  .on('ready', async () => {
    let dockerImages = `${config.docker.image}:${config.docker.tag}`;
    log('清除缓存中...');
    conn.exec('cd /usr/local/src && rm -rf dist', (error, stream) => {
      if (error) {
        log('清除dist文件夹失败');
      } else {
        log('开始上传静态资源...');
        putDir(config.path.localPath, config.path.romotePath, () => {
          log('上传完毕');
          conn.exec(
            `cd /usr/local/src && sh ${config.path.shell} ${dockerImages} ${config.docker.container} ${config.docker.stopContainer}`,
            async (error, stream) => {
              if (error) {
                log('他妈的出错了');
              } else {
                stream.on('data', data => {
                  log(data);
                  
                });
              }
            }
          );
        });
      }
    });
  })
  .connect(config.romote);

